/*
 * Canvas Game Engine - Key Event Manager
 *
 * version: 0.1
 *
 * author: Fabio Rotondo <fabio@rotondo.it>
 *
 */

function CGEKeyHandler ()
{
	this._keys = {};
};


CGEKeyHandler.prototype.add = function ( key_code, cback_down, cback_up )
{
	this._keys [ key_code ] = [ cback_down, cback_up ];
};

CGEKeyHandler.prototype.del = function ( key_code )
{
	this._keys [ key_code ] = null;
};

CGEKeyHandler.prototype.listen = function ( enabled )
{
	var self = this;
	var listener_down = function ( evt ) { self._key_pressed ( evt, 0 ); };
	var listener_up = function ( evt ) { self._key_pressed ( evt, 1 ); };

	if ( enabled )
	{
		window.addEventListener ( 'keydown', listener_down, true);
		window.addEventListener ( 'keyup', listener_up, true);
	} else {
		window.removeEventListener ( 'keydown', listener_down, true );
		window.removeEventListener ( 'keyup', listener_up, true );
	}
};

CGEKeyHandler.prototype._key_pressed = function ( evt, pos )
{
	var kcode = evt.keyCode;
	var cback;

	cbacks = this._keys [ kcode ];
	if ( cbacks && cbacks [ pos ] ) cbacks [ pos ] ();
};

CGE.keys = new CGEKeyHandler ();

CGE.KEY_CURSOR_UP = 38;
CGE.KEY_CURSOR_DOWN = 40;
CGE.KEY_CURSOR_LEFT = 37;
CGE.KEY_CURSOR_RIGHT = 39;
